<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑模型' : '新增模型'"
    width="500px"
    :close-on-click-modal="false"
    :destroy-on-close="true"
    @close="handleClose"
    custom-class="datav-dialog"
    :modal-class="'datav-modal'"
  >
    <dv-decoration-8 class="dialog-header-decoration" :reverse="true" />
    <dv-border-box-8 class="datav-form-container" :dur="5">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
        label-position="right"
        class="model-form"
      >
        <el-form-item label="模型名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入模型名称" maxlength="50" show-word-limit />
        </el-form-item>
        
        <el-form-item label="状态" prop="enable">
          <el-switch
            v-model="form.enable"
            active-text="启用"
            inactive-text="禁用"
            :active-value="true"
            :inactive-value="false"
          />
        </el-form-item>
        
        <el-form-item label="Word文档" prop="fileWord">
          <div class="file-upload-container">
            <el-upload
              class="template-file-uploader"
              action="#"
              :http-request="uploadWord"
              :show-file-list="false"
              :before-upload="beforeWordUpload"
              accept=".doc,.docx"
            >
              <el-button type="primary" class="tech-button tech-button--primary" :loading="submitting">
                <el-icon><Upload /></el-icon>
                {{ form.fileId ? '重新上传Word' : '上传Word文档' }}
              </el-button>
            </el-upload>
            <div v-if="form.fileId" class="file-uploaded">
              <el-icon><Document /></el-icon>
              <span>已上传Word文档</span>
            </div>
          </div>
        </el-form-item>
      </el-form>
    </dv-border-box-8>
    
    <template #footer>
      <dv-border-box-1 class="datav-dialog-footer-box">
        <div class="datav-dialog-footer">
          <el-button @click="handleClose" class="tech-button">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitting" class="tech-button tech-button--primary">
            保存
          </el-button>
        </div>
      </dv-border-box-1>
    </template>
    <dv-decoration-8 class="dialog-footer-decoration" />
  </el-dialog>
</template>

<script>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { app, ensureLogin } from '../../utils/cloudbase'
import dayjs from 'dayjs'
import { Plus, Upload, Document } from '@element-plus/icons-vue'

export default {
  name: 'ModelFormDialog',
  components: {
    Plus,
    Upload,
    Document
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    editData: {
      type: Object,
      default: () => null
    }
  },
  emits: ['update:visible', 'refresh'],
  setup(props, { emit }) {
    // 表单引用
    const formRef = ref(null)
    
    // 对话框可见性
    const dialogVisible = computed({
      get: () => props.visible,
      set: (val) => emit('update:visible', val)
    })
    
    // 是否为编辑模式
    const isEdit = computed(() => !!props.editData)
    
    // 表单数据
    const form = reactive({
    _id: '', // 添加 _id 字段用于更新操作
      name: '',
      enable: true,
      fileId: '',
      fileWord: null
    })
    
    // 提交状态
    const submitting = ref(false)
    
    // 表单验证规则
    const rules = {
      name: [
        { required: true, message: '请输入模型名称', trigger: 'blur' },
        { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
      ],
      fileWord: [
        { required: true, message: '请上传Word文档', trigger: 'change' }
      ]
    }
    
    // 重置表单
    const resetForm = () => {
      form.name = ''
      form.enable = true
      form.fileId = ''
      form.fileWord = null
      if (formRef.value) {
        formRef.value.resetFields()
      }
    }
    
    // 监听编辑数据变化
    watch(() => props.editData, (newVal) => {
      if (newVal) {
        // 填充表单数据
        form.name = newVal.name || ''
        form.enable = newVal.enable !== undefined ? newVal.enable : true
        form.fileId = newVal.fileId || ''
        
        // 如果有文件ID，设置文件已上传状态
        if (newVal.fileId) {
          form.fileWord = true // 标记为已上传状态
        }
      } else {
        // 重置表单
        resetForm()
      }
    }, { immediate: true })
    
    // 关闭对话框
    const handleClose = () => {
      dialogVisible.value = false
      resetForm()
    }
    
    // Word文件上传前验证
    const beforeWordUpload = (file) => {
      const isDocx = file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
      const isDoc = file.type === 'application/msword'
      
      if (!isDocx && !isDoc) {
        ElMessage.error('只能上传 .doc/.docx 格式的文件!')
        return false
      }
      
      const isLt10M = file.size / 1024 / 1024 < 3
      if (!isLt10M) {
        ElMessage.error('文件大小不能超过 3MB!')
        return false
      }
      
      return true
    }
    
    // 生成存储路径
    const generatePath = (prefix) => {
      const date = dayjs().format('YYYYMMDD')
      const time = dayjs().format('HHmmss')
      return `${prefix}/${date}/${time}`
    }
    
    // Word文件上传处理
    const uploadWord = async (options) => {
      try {
        // await ensureLogin()
        submitting.value = true
        
        const file = options.file
        // 转换为Base64
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = async (e) => {
          const base64Content = e.target.result.split(',')[1]
          
          try {
            const result = await app.callFunction({
              name: 'admin-file-upload',
              data: {
                fileContent: base64Content,
                fileName: file.name,
                folder: generatePath('template')
              }
            })
            
            if (result.result && result.result.code === 0) {
              form.fileId = result.result.data.fileId
              form.fileWord = true // 标记为已上传
              ElMessage.success('Word文档上传成功')
            } else {
              ElMessage.error(result.result?.message || 'Word文档上传失败')
            }
          } catch (error) {
            console.error('Word文档上传失败:', error)
            ElMessage.error('Word文档上传失败')
          } finally {
            submitting.value = false
          }
        }
      } catch (error) {
        console.error('Word文档读取失败:', error)
        ElMessage.error('Word文档读取失败')
        submitting.value = false
      }
    }
    
    // 提交表单
    const submitForm = async () => {
      if (!formRef.value) return
      
      await formRef.value.validate(async (valid) => {
        if (!valid) return
        
        try {
          submitting.value = true
          
          // 准备提交的数据
          const submitData = {
            name: form.name,
            enable: form.enable,
            fileId: form.fileId
          }
          
          // 调用云函数保存数据
          const action = isEdit.value ? 'update' : 'create'
          const functionData = {
            action,
            data: submitData
          }
          
          // 如果是编辑模式，添加ID
          if (isEdit.value && props.editData._id) {
            functionData.data._id = props.editData._id
          }
          
          const res = await app.callFunction({
            name: 'admin-resume-model-crud',
            data: functionData
          })
          
          if (res.result && res.result.code === 0) {
            ElMessage.success(isEdit.value ? '编辑成功' : '添加成功')
            dialogVisible.value = false
            // 确保触发刷新事件
            emit('refresh')
          } else {
            ElMessage.error(res.result?.message || (isEdit.value ? '编辑失败' : '添加失败'))
          }
        } catch (error) {
          console.error(isEdit.value ? '编辑失败:' : '添加失败:', error)
          ElMessage.error(isEdit.value ? '编辑失败' : '添加失败')
        } finally {
          submitting.value = false
        }
      })
    }
    
    return {
      formRef,
      dialogVisible,
      isEdit,
      form,
      rules,
      submitting,
      handleClose,
      beforeWordUpload,
      uploadWord,
      submitForm
    }
  }
}
</script>

<style>
.el-dialog {
  background-color: rgba(0, 19, 47, 0.9) !important;
  border: 1px solid rgba(0, 192, 255, 0.5) !important;
  box-shadow: 0 0 15px rgba(0, 192, 255, 0.3) !important;
  border-radius: 4px !important;
  backdrop-filter: blur(5px);
  background: rgba(0, 19, 47) !important;
  overflow: hidden !important;
}
.el-dialog__title {
  color: #00c0ff !important;
  font-weight: bold !important;
}
.el-input__count-inner{
  background: inherit !important;
}
</style>
<style scoped>
.model-form {
  max-height: 60vh;
  overflow-y: auto;
  padding: 20px;
  color: #00c0ff;
}

.datav-form-container {
  width: 100%;
  height: auto;
  padding: 10px;
  background-color: rgba(0, 19, 47, 0.8);
}

:deep(.dv-border-box-8) {
  --dv-bb8-color: rgba(0, 192, 255, 0.6);
}

.datav-dialog-footer-box {
  width: 100%;
  height: 50px;
}

.datav-dialog-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  height: 100%;
  padding: 0 20px;
}

:deep(.datav-dialog) {
  background-color: rgba(0, 19, 47, 0.9) !important;
  border: 1px solid rgba(0, 192, 255, 0.5) !important;
  box-shadow: 0 0 15px rgba(0, 192, 255, 0.3) !important;
  border-radius: 4px !important;
  backdrop-filter: blur(5px);
  background: rgba(0, 19, 47) !important;
  overflow: hidden !important;
}

:deep(.datav-dialog .el-dialog) {
  background-color: rgba(0, 19, 47, 0.9) !important;
  border: 1px solid rgba(0, 192, 255, 0.5) !important;
  box-shadow: 0 0 15px rgba(0, 192, 255, 0.3) !important;
}

:deep(.datav-dialog .el-dialog__header) {
  background-color: rgba(0, 30, 60, 0.8) !important;
  border-bottom: 1px solid rgba(0, 192, 255, 0.3) !important;
  padding: 15px 20px !important;
  position: relative;
}

.dialog-header-decoration {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 30px;
  z-index: 1;
}

.dialog-footer-decoration {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 30px;
  z-index: 1;
}

:deep(.datav-dialog .el-dialog__headerbtn .el-dialog__close) {
  color: #00c0ff !important;
}

:deep(.datav-dialog .el-dialog__body) {
  background-color: rgba(0, 19, 47, 0.8) !important;
  padding: 20px !important;
  color: #00c0ff !important;
}

:deep(.datav-dialog .el-dialog__footer) {
  background-color: rgba(0, 30, 60, 0.8) !important;
  border-top: 1px solid rgba(0, 192, 255, 0.3) !important;
  padding: 10px 20px !important;
  height: 70px;
}

:deep(.el-overlay) {
  background-color: rgba(0, 10, 30, 0.7) !important;
  backdrop-filter: blur(3px);
}

:deep(.dv-border-box-1) {
  --dv-bb1-color: rgba(0, 192, 255, 0.5);
}

:deep(.el-form-item__label) {
  color: #00c0ff !important;
}

:deep(.el-input__wrapper) {
  background-color: rgba(0, 30, 60, 0.6) !important;
  border: 1px solid rgba(0, 192, 255, 0.5) !important;
  box-shadow: none !important;
}

:deep(.el-input__inner) {
  color: #ffffff !important;
}

:deep(.el-switch__core) {
  border-color: rgba(0, 192, 255, 0.5) !important;
  background-color: rgba(0, 30, 60, 0.6) !important;
}

:deep(.el-switch.is-checked .el-switch__core) {
  background-color: #00c0ff !important;
}

.file-upload-container {
  display: flex;
  align-items: center;
}

.file-uploaded {
  display: flex;
  align-items: center;
  margin-left: 10px;
  color: #00c0ff;
}

.file-uploaded .el-icon {
  margin-right: 5px;
}

:deep(.el-button.tech-button--primary) {
  background-color: rgba(0, 192, 255, 0.2) !important;
  border-color: rgba(0, 192, 255, 0.7) !important;
  color: #00c0ff !important;
}

:deep(.el-button.tech-button--primary:hover) {
  background-color: rgba(0, 192, 255, 0.4) !important;
  border-color: #00c0ff !important;
  color: #ffffff !important;
  box-shadow: 0 0 10px rgba(0, 192, 255, 0.5) !important;
}

:deep(.el-button.tech-button) {
  background-color: rgba(0, 30, 60, 0.6) !important;
  border-color: rgba(0, 192, 255, 0.3) !important;
  color: rgba(0, 192, 255, 0.8) !important;
}

:deep(.el-button.tech-button:hover) {
  background-color: rgba(0, 30, 60, 0.8) !important;
  border-color: rgba(0, 192, 255, 0.7) !important;
  color: #ffffff !important;
}
</style>